<template>
  <div>
    <div style="height:28px;padding:5px">
      <el-button-group>
        <el-button size="mini" type="primary" @click="popSchBox" icon="el-icon-search">搜索</el-button>
        <el-button size="mini" type="primary" @click="popEdtBox" icon="el-icon-edit">编辑</el-button>
        <el-button size="mini" type="primary" @click="departmentDel" icon="el-icon-delete">删除</el-button>
      </el-button-group>
      <el-button-group>
        <el-button
          size="mini"
          type="primary"
          @click="checkAll"
          icon="el-icon-circle-check-outline"
        >全选</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="uncheckAll"
          icon="el-icon-circle-close-outline"
        >取消</el-button>
      </el-button-group>
    </div>
    <div>
      <hr style="border:1 dashed " width="100%" color="#DCDFE6" size="1">
    </div>
    <div>
      <ag-grid-vue
        ref="grid"
        :columnDefs="columnDefs"
        :rowData="rowData"
        :style="{ height: gridHeight }"
        :pagination="false"
        :getRowNodeId="function(params){return params.AutoId}"
        row-selection="multiple"
        class="ag-theme-material"
        @grid-ready="onGridReady"
        @rowDoubleClicked="popEdtBox"
      ></ag-grid-vue>
      <el-pagination
        :total="rowsCount"
        :current-page="currentPage"
        :page-sizes="[10, 15, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="currentPageSelect"
      ></el-pagination>
    </div>
    <DepartmentSearchBox @searchBtnClick="listDepartmentByDefault" ref="schBox"/>
    <DepartmentEditor
      ref="edtBox"
      :departmentmodel="departmentModel"
      @departmentSaveComplete="departmentSaved"
      @departmentDelComplete="departmentDeleted"
    />
  </div>
</template>

<script>
import { AgGridVue } from 'ag-grid-vue'
import { delDepartments, listDepartment } from '@/api/department'
import DepartmentRenderer from '@/components/CellRenderer/DepartmentRenderer.vue'
import DepartmentSearchBox from '@/components/SearchBox/DepartmentSearchBox.vue'
import DepartmentEditor from '@/components/EditDialog/DepartmentEditor.vue'

export default {
  components: {
    AgGridVue,
    DepartmentRenderer,
    DepartmentSearchBox,
    DepartmentEditor
  },
  data() {
    return {
      columnDefs: [
        { headerName: '', field: 'chk', width: 50, checkboxSelection: true },
        { headerName: '编码', field: 'Code', sortable: true, filter: true },
        { headerName: '名称', field: 'Name', sortable: true, filter: true },
        {
          headerName: '上级部门',
          field: 'Parent',
          cellRendererFramework: 'DepartmentRenderer',
          sortable: true,
          filter: true
        }
      ],
      rowData: null,
      gridHeight: '',
      rowsCount: null,
      currentPage: 1,
      pageSize: 15,
      gridApi: null,
      columnApi: null,
      departmentModel: {}
    }
  },
  methods: {
    onGridReady(params) {
      this.gridApi = params.api
      this.columnApi = params.columnApi
    },
    currentPageSelect(pageIdx) {
      if (pageIdx !== this.currentPage) {
        this.currentPage = pageIdx
      }
      const start = (pageIdx - 1) * this.pageSize
      const end = start + this.pageSize
      this.listDepartment(start, end, this.getConditions())
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPageSelect(1)
    },
    getConditions() {
      const conditions = [
        {
          Key: 'Name',
          Op: 'like',
          Value: '%' + this.$refs.schBox.form.kwName + '%'
        },
        {
          Key: 'Code',
          Op: 'like',
          Value: '%' + this.$refs.schBox.form.kwCode + '%'
        }
      ]
      const dptId = this.$refs.schBox.form.parentId
      if (dptId) {
        conditions.push({ Key: 'Parent', Op: '=', Value: dptId })
      }
      return conditions
    },
    listDepartment(pos, size, conditions) {
      listDepartment(pos, size, conditions)
        .then(response => {
          console.log(response)
          this.rowData = response.Data
          this.rowsCount = response.Cnt
        })
        .catch(error => {
          console.log(error)
          this.rowData = []
          this.rowsCount = 0
        })
    },
    checkAll() {
      this.gridApi.selectAll()
    },
    uncheckAll() {
      this.gridApi.deselectAll()
    },
    popSchBox() {
      this.$refs.schBox.dialogVisible = true
    },
    popEdtBox() {
      const selectedNodes = this.gridApi.getSelectedNodes()
      const selectedData = selectedNodes.map(node => node.data)
      if (selectedData.length > 1) {
        this.$alert('请只选中一行记录', '提示')
        return
      } else if (selectedData.length === 0) {
        if (!this.departmentModel || this.departmentModel.AutoId > 0) {
          //防止每打开一次，watch都会执行一次
          let dpt_tmp = {}
          //this.setDefault(dpt_tmp)
          this.departmentModel = dpt_tmp
        }
      } else {
        this.departmentModel = this.rowData.find(function(item) {
          return item.AutoId === selectedData[0].AutoId
        })
      }
      this.$refs.edtBox.dialogVisible = true
    },
    departmentDel() {
      const selectedNodes = this.gridApi.getSelectedNodes()
      const selectedData = selectedNodes.map(node => node.data)
      if (selectedData.length === 0) {
        this.$message('请先选中需要删除的档案')
        return
      }
      this.$confirm(
        '将会删除' + selectedData.length + '笔记录, 是否继续?',
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
      )
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const models = []
          for (let idx in selectedData) {
            models.push(
              this.rowData.find(function(item) {
                return item.AutoId === selectedData[idx].AutoId
              })
            )
          }
          delDepartments(JSON.stringify(models))
            .then(response => {
              if (response.Result === 0) {
                for (let rIdx in this.rowData) {
                  for (let mIdx in response.Data) {
                    if (this.rowData[rIdx].AutoId === response.Data[mIdx]) {
                      this.rowData.splice(rIdx, 1)
                    }
                  }
                }
                const faild = models.length - response.Data.length
                if (faild > 0) {
                  this.$message({
                    message: '共有' + faild + '笔记录删除失败',
                    type: 'warning'
                  })
                } else {
                  this.$message('全部删除成功')
                }
                loading.close()
              } else {
                console.log(response.Message)
              }
            })
            .catch(error => {
              console.log(JSON.stringify(error))
              loading.close()
            })
        })
        .catch(() => {})
    },
    listDepartmentByDefault() {
      console.log(this.$refs.schBox.form)
      this.listDepartment(
        this.currentPage - 1,
        this.pageSize,
        this.getConditions()
      )
    },

    departmentSaved(params) {
      if (params.Flag === 1) {
        this.rowData.push(params)
      } else {
        this.gridApi.getRowNode(params.AutoId).setData(params)
      }
    },
    departmentDeleted(params) {
      for (let idx in this.rowData) {
        if (this.rowData[idx].AutoId === params) {
          this.rowData.splice(idx, 1)
          break
        }
      }
    }
  },
  mounted() {
    this.gridHeight = window.innerHeight - 30 - 50 - 32 - 5 - 38 - 10 + 'px'
    const that = this
    window.onresize = function changeGridSize() {
      that.gridHeight = window.innerHeight - 30 - 50 - 32 - 5 - 38 - 10 + 'px'
    }
    this.$refs.schBox.searchBtnClick = this.listDepartmentByDefault
    this.listDepartmentByDefault()
  },
  beforeMount() {}
}
</script>

<style lang="scss">
@import "../../../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../../../node_modules/ag-grid-community/dist/styles/ag-theme-balham.css";
@import "../../../node_modules/ag-grid-community/dist/styles/ag-theme-material.css";
</style>

